package com.getguang.superstore.search

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.apollo.ext.optionalOrAbsent
import com.starblink.rocketreserver.DiscountMerchantsListV3Query
import com.starblink.rocketreserver.SearchMerchantWebsQuery
import com.starblink.rocketreserver.type.MerchantWebSearchReq
import kotlinx.coroutines.launch

/**
 *  Create by yuanl at 2023/10/12
 **/
class SsdSearchVM : BaseViewModel() {

    val list = mutableListOf<Any>()

    val dataObserver by lazy {
        MutableLiveData<Boolean>()
    }

    var searchContent: String? = null

    var pageNo = 1

    private var randomSeed: Int? = null

    var deals: Array<String>? = null

    private val fakeDealsOpt by lazy {
        mutableListOf("").optionalOrAbsent()
    }

    private var defaultImagesIndex: Int? = null

    fun loadData(moreData: Boolean = false) {
        if (searchContent.isNullOrEmpty()) {
            return
        }
        if (moreData) {
            pageNo ++
        } else {
            pageNo = 1
            randomSeed = null
            list.clear()
            defaultImagesIndex = null
        }
        viewModelScope.launch {
            graphQLQuery(
                DiscountMerchantsListV3Query(
                    pageNo = pageNo,
                    pageSize = 20,
//                    dealIds = if (deals?.isNotEmpty() == true) {
//                        deals?.toList().optionalOrAbsent()
//                    } else {
//                        fakeDealsOpt
//                    },
                    home = false.optionalOrAbsent(),
                    randomSeed = randomSeed.optionalOrAbsent(),
                    merchantName = searchContent.optionalOrAbsent(),
                    defaultImagesIndex = defaultImagesIndex.optionalOrAbsent()
                )
            )?.data.let {
                randomSeed = it?.discountMerchantsListV3?.randomSeed
                defaultImagesIndex = it?.discountMerchantsListV3?.defaultImagesIndex
                val merchants = it?.discountMerchantsListV3?.merchantWebs?.map { it.merchantWebVOF }
                if (merchants?.isNotEmpty() == true) {
                    list.addAll(merchants)
                    dataObserver.postValue(true)
                } else {
                    dataObserver.postValue(false)
                }
            }
        }
    }

}